---
title: Pointers and References
---

In C++, pointers and references are fundamental concepts that allow for direct memory manipulation and efficient data passing. They are crucial for understanding how C++ manages memory and interacts with hardware, and they represent a significant difference from JavaScript's memory model.

## Pointer Concept and Syntax

A **pointer** is a variable that stores the memory address of another variable. It "points" to a location in memory where a value is stored. Pointers are powerful but require careful handling.

### Declaring and Initializing Pointers

*   `int* ptr;` // Declares a pointer to an integer.
*   `int* ptr = &variable;` // Initializes `ptr` with the address of `variable`.

### Dereferencing Pointers

*   `*ptr` // Accesses the value at the memory address stored in `ptr`.

<UniversalEditor title="Pointer Basics Comparison" compare={true}>
```javascript !! js
// JavaScript: No direct pointers, variables hold values or references to objects.
let num = 10;
let obj = { value: 20 };

// In JavaScript, when you assign an object, you're copying the reference.
let anotherObj = obj;
anotherObj.value = 30;
console.log(obj.value); // 30
```

```cpp !! cpp
// C++: Pointers
#include <iostream>

int main() {
  int num = 10; // A regular integer variable
  int* ptr = &num; // Declare a pointer 'ptr' and store the address of 'num'

  // std::cout << "Value of num: " << num << std::endl; // 10
  // std::cout << "Address of num: " << &num << std::endl; // Memory address
  // std::cout << "Value of ptr (address of num): " << ptr << std::endl; // Same memory address
  // std::cout << "Value at address pointed by ptr: " << *ptr << std::endl; // 10 (dereferencing)

  *ptr = 20; // Change the value of num through the pointer
  // std::cout << "New value of num: " << num << std::endl; // 20

  return 0;
}
```
</UniversalEditor>

## Reference Concept and Syntax

A **reference** is an alias (an alternative name) for an already existing variable. Once a reference is initialized to a variable, it cannot be reseated to refer to another variable. References are often used for passing arguments to functions by reference.

### Declaring and Initializing References

*   `int& ref = variable;` // Declares a reference `ref` and binds it to `variable`.

<UniversalEditor title="Reference Basics Comparison" compare={true}>
```javascript !! js
// JavaScript: Object references behave somewhat like C++ references.
let data = { count: 5 };
let alias = data; // 'alias' refers to the same object as 'data'

alias.count = 10;
console.log(data.count); // 10

// However, JavaScript references can be reassigned:
alias = { count: 15 }; // 'alias' now refers to a new object
console.log(data.count); // Still 10
```

```cpp !! cpp
// C++: References
#include <iostream>

int main() {
  int value = 100; // A regular integer variable
  int& ref = value; // Declare a reference 'ref' and bind it to 'value'

  // std::cout << "Value: " << value << std::endl; // 100
  // std::cout << "Value via ref: " << ref << std::endl; // 100

  ref = 200; // Change the value of 'value' through the reference
  // std::cout << "New value: " << value << std::endl; // 200

  // References cannot be reseated:
  // int anotherValue = 300;
  // ref = anotherValue; // This assigns the value of anotherValue to value, not reseats ref

  return 0;
}
```
</UniversalEditor>

## Pointer Arithmetic

Pointer arithmetic involves performing arithmetic operations on pointers. It's primarily used with arrays.

*   `ptr + n`: Moves the pointer `n` elements forward (not `n` bytes).
*   `ptr - n`: Moves the pointer `n` elements backward.
*   `ptr1 - ptr2`: Calculates the number of elements between `ptr1` and `ptr2`.

<UniversalEditor title="Pointer Arithmetic Comparison" compare={true}>
```javascript !! js
// JavaScript: Array indexing is similar to pointer arithmetic conceptually.
let arr = [10, 20, 30, 40, 50];
console.log(arr[0]); // 10
console.log(arr[0 + 2]); // 30 (accessing element at index 2)
```

```cpp !! cpp
// C++: Pointer Arithmetic
#include <iostream>

int main() {
  int arr[] = {10, 20, 30, 40, 50};
  int* ptr = arr; // ptr points to the first element (arr[0])

  // std::cout << "First element: " << *ptr << std::endl; // 10

  ptr = ptr + 2; // Move ptr two integer positions forward (to arr[2])
  // std::cout << "Element after ptr + 2: " << *ptr << std::endl; // 30

  int* ptr2 = &arr[4]; // ptr2 points to arr[4]
  // std::cout << "Elements between ptr and ptr2: " << (ptr2 - ptr) << std::endl; // 2

  return 0;
}
```
</UniversalEditor>

## Function Pointers

A **function pointer** is a pointer that points to the memory address of a function. It allows you to call functions indirectly, pass functions as arguments, or store them in data structures.

<UniversalEditor title="Function Pointer Comparison" compare={true}>
```javascript !! js
// JavaScript: Functions are first-class citizens, can be passed as arguments.
function multiply(a, b) {
  return a * b;
}

function operate(func, x, y) {
  return func(x, y);
}

console.log(operate(multiply, 5, 4)); // 20
```

```cpp !! cpp
// C++: Function Pointers
#include <iostream>

int multiply(int a, int b) {
  return a * b;
}

int operate(int (*funcPtr)(int, int), int x, int y) {
  return funcPtr(x, y);
}

// In main function:
// int (*ptrToMultiply)(int, int) = &multiply; // Declare and initialize function pointer
// std::cout << operate(ptrToMultiply, 5, 4) << std::endl; // 20
```
</UniversalEditor>

## Differences between Pointers and References

| Feature           | Pointer                                  | Reference                                |
| :---------------- | :--------------------------------------- | :--------------------------------------- |
| **Initialization**| Can be declared without initialization (but dangerous) | Must be initialized at declaration       |
| **Null Value**    | Can be `nullptr` (or `NULL`)             | Cannot be null                           |
| **Reassignment**  | Can be reassigned to point to different variables | Cannot be reseated (always refers to the same variable) |
| **Memory Address**| Stores a memory address                  | Is an alias; doesn't store its own address (conceptually) |
| **Dereference**   | Requires `*` to dereference              | No explicit dereference operator needed (used directly) |

## Common Pointer Errors

*   **Dangling Pointers:** Pointers that point to memory that has been deallocated.
*   **Wild Pointers:** Uninitialized pointers that point to arbitrary memory locations.
*   **Null Pointer Dereference:** Attempting to dereference a `nullptr`, leading to a crash.
*   **Memory Leaks:** Forgetting to `delete` dynamically allocated memory (covered in Module 2).

## Comparison with JavaScript References

JavaScript does not have explicit pointers or references in the C++ sense. Instead, JavaScript variables that hold objects (including arrays and functions) store **references** to those objects. These references are managed by the JavaScript engine's garbage collector.

*   **No Manual Memory Management:** You don't `new` or `delete` objects in JavaScript; the GC handles it.
*   **No Pointer Arithmetic:** You cannot perform arithmetic operations on JavaScript references.
*   **References can be Reassigned:** Unlike C++ references, JavaScript references can be reassigned to point to different objects.

Essentially, JavaScript's object references behave somewhat like C++ pointers to objects, but with automatic memory management and without the ability to perform pointer arithmetic or direct memory access.

---

### Practice Questions:
1.  Explain the core difference between a C++ pointer and a C++ reference. When would you choose to use one over the other?
2.  Write a C++ function that takes an integer pointer as an argument, increments the value it points to by 5, and then prints the new value. Demonstrate how to call this function from `main`.
3.  What is a dangling pointer, and how can you avoid creating one in C++?

### Project Idea:
*   Implement a simple dynamic array (similar to `std::vector`) in C++ using raw pointers. Your implementation should include functions for adding elements, removing elements, resizing the array, and accessing elements by index. Pay close attention to memory allocation and deallocation to prevent leaks and dangling pointers.
